$(function(){
	$("#slideshow ul").each(function(){
		s = new Slideshow($(this));
	});
});

function Slideshow(ul){
	this.objTimeout = null;
	this.speed = 700;
	this.timeout = 4000;
	this.holder = ul.parent();
	this.slides = [];
	this.controls = null;
	var _this = this;
	ul.children("li").each(function(){
		var s = {
			image: new Image(),
			title: $(this).children("h1").text(),
			description: $(this).children("p").text(),
			link: $(this).children("a").attr("href")
		};
		s.image.src = $(this).find("img").attr("src");
		_this.slides.push(s);
	});
	this.position = 0;
	ul.remove();
	
	// draw the GUI
	$('<div class="slider visible"><a href=""><img src="" /></a><h1></h1><p></p></div>').appendTo(this.holder);
	$('<div class="slider hidden"><a href=""><img src="" /></a><h1></h1><p></p></div>').appendTo(this.holder);
	// draw slideshow controls
	_this.controls = $('<ul class="controls">').prependTo(this.holder);
	$(this.slides).each(function(index){
		_this.controls.append('<li index="'+index+'">'+index+'</li>');
	});
	_this.controls.children("li").eq(0).addClass("active");
	_this.controls.children("li").click(function(){
		var index = parseInt($(this).attr("index"));
		_this.play(index);
	});
	this.incrementPosition = function(){
		this.position++;
		this.position = this.position >= this.slides.length ? 0 : this.position;
	}
	this.setSlides = function(pos1,pos2){
		var vis = this.holder.find(".slider.visible");
		var hid = this.holder.find(".slider.hidden");
		
		var s1 = this.slides[pos1];
		hid.find('img').attr("src", s1.image.src);
		hid.find('a').attr("href", s1.link);
		hid.find('h1').html(s1.title);
		hid.find('p').html(s1.description);
		
		var s2 = this.slides[pos2];
		vis.find('img').attr("src", s2.image.src);
		vis.find('a').attr("href", s2.link);
		vis.find('h1').html(s2.title);
		vis.find('p').html(s2.description);
	};
	this.play = function(position){
		
		if(this.objTimeout){
			clearTimeout(this.objTimeout);
		}
		
		position = parseInt(position)>=0 ? (position<this.slides.length ? position : this.slides.length-1) : 0;
		this.position=position;
		
		pos1 = position;
		pos2 = pos1+1;
		pos2 = pos2>=this.slides.length ? 0 : pos2;
		var vis = this.holder.find(".slider.visible");
		var hid = this.holder.find(".slider.hidden");
		
		this.setSlides(pos1, pos2);
		
		_this = this;
		vis.fadeOut(_this.speed);
		hid.fadeIn({
			speed: _this.speed,
			complete: function(){
				
				vis.removeClass("visible").addClass("hidden");
				hid.removeClass("hidden").addClass("visible");
				_this.controls.children("li").removeClass("active").eq(_this.position).addClass("active");
				_this.incrementPosition();
				_this.objTimeout = setTimeout(function(){
					_this.play(_this.position);
				}, _this.timeout);
			}
		});
	};
	
	this.play();
}